<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" />
<template>
  <div>
    <el-card>
     <!-- 用于选择excel文件 1-->
     <input type="file" ref="excelFileInput" accept=".xlsx,.xls" style="display: none;" @change="handleFileUpload">
      <!-- 筛选区域 -->
      <el-row :gutter="20" type="flex" justify="start" align="middle">
        <el-col :span="7">
          <el-input v-model="searchKey" placeholder="请输入测点编号" clearable
          @keyup.enter.native="searchData"  />
        </el-col>

        <el-col :span="12"  style="display: flex; align-items: center;">
          <el-button id="filter-button" type="primary" @click="searchData">查询</el-button>
          <el-button id="reset-button" type="default" @click="resetFilter ">重置</el-button>
          <!-- <el-upload
            action="http://localhost:8080/measuresInfo/uploadExcel"
            name="file"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            style="margin-left: 10px;"
          >
            <el-button type="success">上传 Excel 文件</el-button>
          </el-upload> -->
           <!-- excel导入按钮 -->
          <el-button type="primary" style="width: 8vw;" @click="importFromExcel">Excel导入</el-button>
           
          <el-button style="margin-left: 10px; width: 8vw;" type="primary" @click="showAddDialog">
            <i class="fas fa-plus"></i>添加测点
          </el-button>

        </el-col>
      </el-row>

      <!-- 列表区 -->
      <div style="height: 60vh">
    <el-skeleton :loading="loading" animated>
      <el-table :data="paginatedData" border height="100%" style="width: 100%; margin-top:20px">
        <el-table-column prop="measuresCode" label="测点编号" />
        <el-table-column prop="measuresType" label="测点类型" />
        <el-table-column prop="sensCode" label="型号" />
        <el-table-column prop="powerPlantName" label="测点名称" />
        <el-table-column prop="sensDesc" label="备注" />
        <el-table-column prop="options" label="操作">
          <template #default="scope">
            <el-button type="primary"  @click="editItem(scope.row)">编辑</el-button>
                <el-button id="delete-button" type="default"  @click="deleteItem(scope.row.measuresCode)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-skeleton>
  </div>

      <!-- 分页 -->
      <template #footer>
        <div style="margin-top: -30px">
          <Pagination :total="total" :current-page.sync="searchForm.current" :total-pages="totalPages"
            @update:currentPage="handlePageChange" />
        </div>
      </template>
    </el-card>
    <!-- 添加测点模态框 -->
    <el-dialog title="添加测点" v-model="addDialogVisible"  class="add-dialog">
      <!-- <p>{{ addDialogVisible? '弹窗应该显示' : '弹窗不应该显示' }}</p> -->
      <el-form ref="addMeasureInfo" :model="addForm" >
        <el-form-item label="测点编号:" >
          <el-input v-model="addForm.measuresCode"></el-input>
        </el-form-item>
        <el-form-item label="测点类型:" >
          <el-input v-model="addForm.measuresType"></el-input>
        </el-form-item>
        <el-form-item label="  型号:" >
          <el-input v-model="addForm.sensCode"></el-input>
        </el-form-item>
        <el-form-item label="测点名称:" >
          <el-input v-model="addForm.powerPlantName"></el-input>
        </el-form-item>
        <el-form-item label="  备注:" >
          <el-input v-model="addForm.sensDesc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false" color="black">取消</el-button>
        <el-button type="primary" @click="addPoint">确定</el-button>
      </template>
    </el-dialog>

    <!-- 编辑测点模态框 -->
    <el-dialog title="编辑测点" v-model="editDialogVisible"  class="edit-dialog">
      <el-form ref="editMeasureInfo" :model="editForm">
        <el-form-item label="测点编号">
          <el-input class="disabled" v-model="editForm.measuresCode"  disabled></el-input>
        </el-form-item>
        <el-form-item label="测点类型">
          <el-input v-model="editForm.measuresType"></el-input>
        </el-form-item>
        <el-form-item label="型号">
          <el-input v-model="editForm.sensCode"></el-input>
        </el-form-item>
        <el-form-item label="测点名称">
          <el-input v-model="editForm.powerPlantName"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editForm.sensDesc"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false" color="black">取消</el-button>
        <el-button type="primary" @click="confirmEdit">保存</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup>
import { computed, onMounted, reactive, ref, watch } from "vue";
import { useRouter } from "vue-router";
import miApi from "@/api/measureInfo";
import Pagination from "@/components/Table/Pagination";
import { ElMessage, ElMessageBox } from "element-plus";


const router = useRouter();
// Dom 挂载之后
onMounted(() => {
  getMeasureInfoData();
});
// 数据
const inputValue = ref("");
const allTableData = ref([]); // 接收后端全部结果
const tableData = ref([]);
const total = computed(() => tableData.value.length); // 总记录条数
const totalPages = ref(1); // 总页数
const searchKey = ref("");
const addDialogVisible = ref(false); // 添加此响应式变量用于控制模态框显示
const editDialogVisible = ref(false); // 新增编辑对话框的响应式变量
const dialogVisible = ref(false);
const displayData = ref(null);
// 监听 allTableData 的变化，并同步更新 tableData
watch(allTableData, (newData) => {
  tableData.value = [...newData];
});

watch(total, (newData) => {
  totalPages.value = Math.ceil(newData / searchForm.size);
});

const handlePageChange = (page) => {
  searchForm.current = page;
};
// //时间筛选
// const timeFrame = ref('')

// 搜索条件
const searchForm = reactive({
  current: 1,
  size: 10,
});

// 定义 addForm
const addForm = reactive({
  measuresCode: "",
  measuresType: "",
  sensCode: "",
  powerPlantName: "",
  sensDesc: "",
});

// 获取诊断结果列表
const getMeasureInfoData = async () => {
  // 分页条件查询
  const res = await miApi.getmeasureInfoData({ size: null, current: null }); // 查询全部
  // console.log(res);
  if (res.data.status) {
    // 用all前缀来接收保存
    allTableData.value = res.data.data;
  } else {
    ElMessage.error("获取后端数据失败");
    console.log(res.data.message);
  }
};

// 分页监听
// 计算当前页需要显示的数据
const paginatedData = computed(() => {
  const start = (searchForm.current - 1) * searchForm.size;
  const end = start + searchForm.size;
  return tableData.value.slice(start, end);
});




const searchData = async () => {
    const queryId = searchKey.value;
    // console.log({ id: queryId })
    if (queryId) {
    try {
      const res1 = await miApi.selectMeasureInfoData(searchKey.value);
      console.log(res1.data);
      if (res1.data) {
        allTableData.value = res1.data.map(item => ({...item, selected: false }));
        tableData.value = [...allTableData.value];
      } else if (res1.data === null) { // 添加判断，处理 res1.data 为 null 的情况
        ElMessage.error("未查询到设备信息");
      } else {
        ElMessage.error("查询设备信息失败");
        console.log(res1.data.message);
      }
    } catch (error) {
      ElMessage.error("与后端通信出现错误");
      console.error(error);
    }
  } else {
    ElMessage.warning("请输入设备名称进行查询");
  }
};



// 定义编辑和删除功能
const editForm = reactive({
  measuresCode: "",
  measuresType: "",
  sensCode: "",
  powerPlantName: "",
  sensDesc: "",
});

const editItem = (row) => {
  // 将选中的行数据复制到 editForm 中
  Object.assign(editForm, row);
  editDialogVisible.value = true;
};



const confirmEdit = async () => {
  try {
    // 添加日志输出，检查 editForm 的内容
    console.log("编辑前的 editForm：", editForm);
    const res = await miApi.updateMeasureInfo(editForm.measuresCode, editForm);
    console.log("更新后的响应：", res);
    if (res.status) {
      ElMessage.success("测点更新成功");
      editDialogVisible.value = false;
      getMeasureInfoData();
    } else {
      ElMessage.error("测点更新失败");
    }
  } catch (error) {
    ElMessage.error("测点更新失败");
    console.error(error);
  }
};




const deleteItem = async (measuresCode) => {
  await ElMessageBox.confirm("此操作将永久删除该测点, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const res = await miApi.deleteMeasureInfoByCode(measuresCode);
    if (res.data.status) {
      ElMessage.success("测点删除成功");
      getMeasureInfoData(); // 刷新表格
    } else {
      ElMessage.error("测点删除失败");
    }
  }).catch(() => {
    ElMessage.info("已取消删除");
  });
};


// 时间筛选数据
const filterData = () => {
  if (timeFrame.value.length === 2) {
    // 确保用户选择了开始时间和结束时间
    const [startTime, endTime] = timeFrame.value;
    tableData.value = allTableData.value.filter((item) => {
      const itemTime = new Date(item.triggerTime);
      return itemTime >= new Date(startTime) && itemTime <= new Date(endTime);
    });
  }
};

// 重置筛选
const resetFilter = async () => {
  try {
    // 重置搜索关键字
    searchKey.value = '';
    // 重新获取数据
    await getMeasureInfoData();
  } catch (error) {
    ElMessage.error("重置筛选时出现错误");
    console.error(error);
  }
};

// 加载loading页面
const loading = ref(true);
watch(
  () => paginatedData.value,
  (newValue) => {
    loading.value =!(newValue && newValue.length > 0);
  },
  // 配置项确保在组件挂载时，立即执行一次回调，以根据初始值正确设置 loading 的状态
  { immediate: true } // 立即执行一次，以确保初始值状态正确
);

// 点击添加测点按钮弹出模态框
const showAddDialog = () => {
  
  addDialogVisible.value = true;

};

//触发excel文件选择对话框。
const importFromExcel = () => {
    // 触发文件选择对话框
    document.querySelector('input[type=file]').click();
};

// 处理excel文件选择后的操作
const handleFileUpload = (event) => {
  //从事件对象event中获取用户选择的文件
  //event.target.files是一个文件列表，[0]表示获取列表中的第一个文件
  const file = event.target.files[0];
  if (file) {
    const formData = new FormData ();
    //将获取到的文件添加到FormData对象中
    //指定了一个键excelFile，这个键在后端接收文件时会用到，用于识别上传的文件
    formData.append ('excelFile', file);
    // 调用后端接口上传文件
    //.then(response => {...})是一个 Promise 的成功处理程序，当后端成功响应请求并返回数据时，会执行这个函数
    miApi.importExcel (formData).then (response => {
      console.log(response);
      if (response.data.status) {
        ElMessage.success (' 设备信息导入成功 ');
        getMeasureInfoData();
      } else {
        ElMessage.error (' 设备信息导入失败--' + response.data.message + '--导入的数据可能已存在');
      }
    }).catch (error => {
        ElMessage.error (' 文件上传出错 ');
        console.log (error);
      });
  }
};

// 添加测点信息
const addPoint = async () => {
  // 检查测点编号是否已存在
  const existingMeasure = allTableData.value.find(item => item.measuresCode === addForm.measuresCode);
  if (existingMeasure) {
    ElMessage.error("测点编号已经存在");
    return;
  }
  try {
    const res = await miApi.addMeasureInfo(addForm);
    if (res.data) {
      ElMessage.success("测点添加成功");
      addDialogVisible.value = false;
      getMeasureInfoData();
      // 重置表单数据
      addForm.measuresCode = "";
      addForm.measuresType = "";
      addForm.sensCode = "";
      addForm.powerPlantName = "";
      addForm.sensDesc = "";
    } else {
      ElMessage.error("测点添加失败");
    }
  } catch (error) {
    ElMessage.error("与后端通信出现错误");
    console.error(error);
  }
};

// 上传文件处理
const handleUploadSuccess = (response) => {
  if (response.code === 200) {
    ElMessage.success("Excel 文件上传并导入成功");
    getFaultDiagnosesTableData(); // 刷新表格数据
    fetchSensorModels(); // 更新传感器型号下拉框
  } else {
    ElMessage.error("Excel 文件上传成功，但导入失败");
  }
};


const handleUploadError = () => {
  ElMessage.error("Excel 文件上传失败");
};
 

</script>

<style scoped lang="scss">
/*筛选-重置-增加按钮*/

/* 弹框样式 */
.el-alert {
  margin-top: 20px;
}
	/* 上传按钮样式 */
.el-button {
    @include button-style;
}


#delete-button,
#reset-button {
    background-color: $color-reset-button;
        &:hover {
        background-color: #babfd3;
}
}

/*card背景、边框*/
.el-card {
  width: 100%;
  background-color: transparent;
  --el-card-border-color: transparent;
}
//设置下padding20px
:deep(.el-card__body) {
  padding: 0 0 20px;
}
/*数据表背景*/
:deep(.el-table) {
  color: $color-font-table; // 字体颜色
  background-color: transparent;
  --el-table-tr-bg-color: transparent;
  --el-table-header-bg-color: transparent;
  --el-table-row-hover-bg-color: transparent;

  // 鼠标悬停时的行样式
  .el-table__body-wrapper {
    .el-table__row {
      &:hover {
        color: $color-font-table-hover; // 悬停时字体颜色
      }
    }
  }
}

/*日期筛选框背景*/
:deep(.el-input__wrapper) {
  background-color: transparent;
}

//对话框设置
:deep(.el-dialog__title) {
    color: white;

}
:deep(.el-form-item__label) {
    color: white;
    text-align: right;
    width:120px;
}
:deep(.el-input__inner) {
      color: white;
}

:deep(.add-dialog) {
  background-color: #14255f;
  width: 30%;
}
:deep(.edit-dialog) {
  background-color: #14255f;
  width: 30%;
}

:deep(.el-input.is-disabled .el-input__wrapper){
    background-color: #14255f!important;
}

:deep([data-v-4c58861a] .el-input__wrapper) {
    background-color: #000C34;
}

</style>